package com.huangwei.socketchat.server;

import java.io.*;
import java.net.Socket;
import java.util.LinkedList;
import java.util.List;

public class ServerSocketThread implements Runnable {
    private static List<ServerSocketThread> clients = new LinkedList<>();
    private Socket socket;
    private String name;

    public ServerSocketThread(Socket socket)  {
        this.socket = socket;
        BufferedReader inputStream;
        try {
            inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf8"));
            name = inputStream.readLine();
            clients.add(this);
            String welcome = "欢迎" + name + "进入房间,当前房间人数" + clients.size();
            send(welcome);
            System.out.println(welcome);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    public void send(String msg) {
        BufferedWriter writer;
        for (ServerSocketThread client : clients) {
            try {
                writer = new BufferedWriter(new OutputStreamWriter(client.socket.getOutputStream(), "utf8"));
                writer.write(msg);
                writer.newLine();
                writer.flush();
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    public void clientMessageListenner() {
        while (true) {
            try {
                BufferedReader inputStream = new BufferedReader(new InputStreamReader(socket.getInputStream(), "utf8"));
                String message = inputStream.readLine();
                if ("byebye".equals(message)) {
                    String msg = name + "离开了房间";
                    System.out.println(msg);
                    clients.remove(this);
                    socket.close();
                    break;
                }
                send(name + ":" + message);
            } catch (IOException e) {
                throw new RuntimeException(e);
            }
        }
    }

    @Override
    public void run() {
        clientMessageListenner();
    }
}
